package com.esdlife.segment_analytics_plugin.segment_analytics_plugin.analytics

import android.content.Context
import com.segment.analytics.kotlin.android.Analytics
import com.segment.analytics.kotlin.core.Analytics
import com.segment.analytics.kotlin.core.compat.Builders.Companion.buildJsonObject
import com.segment.analytics.kotlin.core.emptyJsonObject
import com.segment.analytics.kotlin.core.platform.policies.CountBasedFlushPolicy
import com.segment.analytics.kotlin.core.platform.policies.FrequencyFlushPolicy
import com.segment.analytics.kotlin.core.utilities.toJsonElement
import kotlinx.serialization.json.JsonObject


object SegmentAnalyticsServices {
    private var lastSegmentWriteKey: String? = null
    var analytics: Analytics? = null

    fun initAnalytics(applicationContext: Context, writeKey: String) {
        if (lastSegmentWriteKey == writeKey && analytics != null) return
        shutdown()
        lastSegmentWriteKey = writeKey
        analytics = Analytics(writeKey, applicationContext) {
            this.collectDeviceId = true
            this.trackApplicationLifecycleEvents = true
            this.trackDeepLinks = false
            this.flushInterval = 10
            this.flushPolicies = listOf(
                CountBasedFlushPolicy(3), // Flush after 3 events
                FrequencyFlushPolicy(5000), // Flush after 5 secs
            )
        }
    }

    fun identify(userId: String, params: HashMap<String, Any>? = null) {
        analytics?.identify(userId = userId, traits = params.toJsonObject())
    }

    fun track(name: String, params: HashMap<String, Any>? = null) {
        analytics?.track(
            name = name,
            properties = params.toJsonObject(),
        )
    }

    fun screen(title: String, params: HashMap<String, Any>? = null, category: String? = null) {
        analytics?.screen(
            title = title,
            properties = params.toJsonObject(),
            category = category ?: ""
        )
    }

    fun group(groupId: String, params: HashMap<String, Any>? = null) {
        analytics?.group(
            groupId = groupId,
            traits = params.toJsonObject(),
        )
    }

    private fun HashMap<String, Any>?.toJsonObject(): JsonObject {
        if (this == null) return emptyJsonObject
        return buildJsonObject {
            forEach { entry ->
                when (val value = entry.value) {
                    is Number -> it.put(entry.key, value)
                    is String -> it.put(entry.key, value)
                    is Boolean -> it.put(entry.key, value)
                    else -> it.put(entry.key, value.toJsonElement())
                }
            }
        }
    }


    fun shutdown() {
        kotlin.runCatching {
            analytics?.reset()
            analytics?.shutdown()
            analytics = null
            lastSegmentWriteKey = null
        }
    }
}